import 'dart:io';

import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/apis/common_api.dart';
import 'package:sainbainu/common/apis/group_api.dart';
import 'package:sainbainu/common/http/exception.dart';
import 'package:sainbainu/common/models/response/upload_response.dart';
import 'package:sainbainu/common/repositories/common_repository.dart';
import 'package:sainbainu/common/repositories/group_repository.dart';
import 'package:sainbainu/common/services/ali_oss.dart';
import 'package:sainbainu/common/utils/compress.dart';

import 'package:sainbainu/common/utils/custom_exception.dart';
import 'package:sainbainu/common/utils/image_cropper.dart';
import 'package:sainbainu/common/utils/loading.dart';
import 'package:sainbainu/common/utils/util.dart';
import 'package:sainbainu/common/values/assets_subtype_cn.dart';
import 'package:sainbainu/common/values/sizes.dart';
import 'package:sainbainu/common/widgets/photo_view_saver.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import 'index.dart';

class GroupCreateUpdateController extends GetxController {
  GroupCreateUpdateController();

  final state = GroupCreateUpdateState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();

    state.nameController = TextEditingController()
      ..addListener(() {
        state.groupInfo.groupName = state.nameController.text;
      });
    state.introController = TextEditingController()
      ..addListener(() {
        state.groupInfo.intro = state.introController.text;
      });

    state.groupRepository = GroupRepository(GroupApi());
    state.commonRepository = CommonRepository(CommonApi());

    if (Get.arguments != null && Get.arguments['groupId'] != null) {
      state.groupId = Get.arguments['groupId'] as int;
      getGroupInfo();
    }
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    state.nameController.dispose();
    state.introController.dispose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  /// 详情
  Future<void> getGroupInfo() async {
    var groupInfo = await state.groupRepository.info(state.groupId!);

    state.nameController.text = groupInfo.groupName ?? '';
    state.introController.text = groupInfo.intro ?? '';
    state.groupInfo = groupInfo;
    update(['cover_image']);
  }

  /// 选择封面
  Future<void> handleSelectCover() async {
    AssetEntity? image = await handleChooseImage();
    if (image != null) {
      // 删除之前的oss图片
      if (state.coverKeyName != null && state.coverKeyName!.isNotEmpty) {
        AliOssService.to.deleteFile(state.coverKeyName!);
      }
      try {
        // AssetEntity 转 file 对象
        List<File> fileList = await Util.assetEntityToFiles([image]);
        if (fileList.isEmpty) {
          throw CustomException('图片解析失败，请稍后再试');
        }
        // 压缩
        fileList = await CompressUtil().compressImages(
          CompressImagesOptions(fileList),
        );
        // 裁剪
        var file = await ImageCropperUtil.crop(
          fileList[0],
          compressQuality: 90,
          aspectRatio: ImageCropperRatio(
            ratioX: Get.width,
            ratioY: kGroupCoverHeight,
          ),
        );
        if (file == null) {
          return;
        }
        // 执行上传
        try {
          LoadingUtil.showLoading(text: '上传中...');
          var res = await handleUpload(file);
          state.groupInfo.cover = res.url;
          state.coverKeyName = res.keyName;
          update(['cover_image']);
          LoadingUtil.showSuccess('上传成功');
        } on CustomHttpException catch (e) {
          throw CustomException(e.message);
        } catch (e) {
          throw CustomException('上传失败，请稍后再试');
        }
      } on CustomException catch (e) {
        LoadingUtil.showError(e.message);
      } catch (e) {
        LoadingUtil.showError(e.toString());
      }
    }
  }

  /// 选择图片
  Future<AssetEntity?> handleChooseImage() async {
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      Get.context!,
      pickerConfig: AssetPickerConfig(
        maxAssets: 1,
        requestType: RequestType.image,
        previewThumbnailSize: const ThumbnailSize.square(200),
        pathNameBuilder: (path) {
          if (path.isAll) return '最近';
          return AssetsSubtypeCn.cnMap[path.name] ?? path.name;
        },
      ),
    );
    if (result != null) {
      // 过滤图片大小
      var newImages = await Util.filterAssetsEntiteis(
        result,
        onError: (msg) => LoadingUtil.showInfo(msg),
      );
      return newImages[0];
    }
    return null;
  }

  /// 上传
  Future<UploadResponse> handleUpload(File file) async {
    UploadResponse res = await AliOssService.to.upFile(
      file.path,
      mediaType: UploadMediaType.image,
    );
    return res;
  }

  /// 显示封面操作弹窗
  void handleShowCoverDialog() {
    if (state.groupInfo.cover == null) return;

    handleShowBottomDialog(
      onPreview: () => handlePreviewImage(state.groupInfo.cover!),
      onChoose: () => handleSelectCover(),
    );
  }

  /// ios 风格底部选择器
  Future<void> handleShowBottomDialog({
    required VoidCallback onPreview,
    required VoidCallback onChoose,
  }) async {
    String? res = await showModalActionSheet<String>(
      context: Get.context!,
      style: AdaptiveStyle.iOS,
      actions: [
        SheetAction(
          key: 'preview',
          label: '预览'.tr,
        ),
        SheetAction(
          key: 'choose',
          label: '重新选择'.tr,
          isDestructiveAction: true,
        ),
      ],
    );
    if (res == 'preview') {
      onPreview();
    } else if (res == 'choose') {
      onChoose();
    }
  }

  /// 预览图像
  void handlePreviewImage(String url) {
    Get.to(
      () => PhotoViewSaver(
        images: [url],
        enableDownload: false,
      ),
      transition: Transition.fadeIn,
      fullscreenDialog: true,
    );
  }

  /// 确认提交
  void handleSubmit() async {
    try {
      if (state.groupInfo.groupName == null ||
          state.groupInfo.groupName!.isEmpty) {
        throw CustomException('小组名称不能为空');
      }
      if (state.groupInfo.intro == null || state.groupInfo.intro!.isEmpty) {
        throw CustomException('小组简介不能为空');
      }
      if (state.groupInfo.cover == null || state.groupInfo.cover!.isEmpty) {
        throw CustomException('小组封面不能为空');
      }
      LoadingUtil.showLoading(text: '正在提交');
      if (state.groupId != null) {
        await state.groupRepository.update(state.groupInfo);
      } else {
        await state.groupRepository.create(state.groupInfo);
      }
      LoadingUtil.dismiss();
      await showOkAlertDialog(
        context: Get.context!,
        title: '提交成功'.tr,
        message: '小组资料提交成功，请等待系统审核'.tr,
        okLabel: '知道了'.tr,
        style: AdaptiveStyle.iOS,
      );
      Get.back();
    } on CustomHttpException catch (e) {
      LoadingUtil.showError(e.message);
    } on CustomException catch (e) {
      LoadingUtil.showError(e.toString());
    } catch (e) {
      LoadingUtil.showError('出错啦～');
    }
  }
}
